/**
 * 
 */
package com.armail.client.controller.impl;

import java.util.List;

import javax.ws.rs.core.MediaType;

import com.armail.client.controller.InboxController;
import com.armail.client.di.Context;
import com.armail.client.dto.Mail;
import com.armail.client.view.InboxView;
import com.armail.client.view.InboxViewListener;
import com.google.inject.Inject;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.GenericType;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;

/**
 * @author arpit
 *
 */
public class InboxControllerImpl implements InboxController, InboxViewListener{

	private static final String REST_URI = "http://localhost:8080/com-armail-server/";
	private static final String GET_MAILS = "/mails/getAllmails/";
	private static final String SEND_MAIL = "/mails/send";
	private InboxView inboxView;
	
	@Inject
	private InboxControllerImpl (InboxView inboxView) {
		this.inboxView = inboxView;
	}
	
	public List<Mail> getMails() {
		ClientConfig config = new DefaultClientConfig();  
        Client client = Client.create(config);  
        WebResource resource = client.resource(REST_URI);  
        
        WebResource employeeResource = resource.path("/rest/").path(GET_MAILS).path(Context.getUser().getId()+""); 
        final ClientResponse response = employeeResource.accept(MediaType.APPLICATION_XML).get(ClientResponse.class);
        return response.getEntity(new GenericType<List<Mail>>() {});
	}
	
	//@Override
	public void onSend(Mail mail) {
		ClientConfig config = new DefaultClientConfig();  
        Client client = Client.create(config);  
        WebResource resource = client.resource(REST_URI);  
        
        WebResource employeeResource = resource.path("/rest/").path(SEND_MAIL); 
        final ClientResponse response = employeeResource.accept(MediaType.APPLICATION_XML).post(ClientResponse.class, mail);
        Mail sentMail = response.getEntity(Mail.class);
	}

	@Override
	public void activate() {
		inboxView.setModel(getMails());
		inboxView.attach();
	}

	@Override
	public void deactivate() {
		inboxView.detach();
	}
}
